package top.mollysu.sell.controller.seller;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import top.mollysu.sell.enums.ResultEnum;
import top.mollysu.sell.form.CategoryForm;
import top.mollysu.sell.pojo.ProductCategory;
import top.mollysu.sell.service.CategoryService;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/seller/category")
public class SellerCategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ModelAndView list(Map<String, Object> map) {
        List<ProductCategory> categoryList = categoryService.findAll();
        map.put("categoryList", categoryList);
        return new ModelAndView("category/list.btl", map);
    }

    @GetMapping("/edit")
    public ModelAndView edit(@RequestParam(value = "categoryId", required = false) Integer categoryId,
                             Map<String, Object> map) {
        if (categoryId != null) {
            ProductCategory productCategory = categoryService.findOne(categoryId);
            map.put("category", productCategory);
        }
        return new ModelAndView("category/edit.btl", map);
    }

    @PostMapping("/save")
    public ModelAndView save(@Valid CategoryForm categoryForm,
                             BindingResult bindingResult,
                             Map<String, Object> map) {
        if (bindingResult.hasErrors()) {
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            return new ModelAndView("common/error.btl", map);
        }

        ProductCategory productCategory = new ProductCategory();
        BeanUtils.copyProperties(categoryForm, productCategory);
        if (categoryForm.getCategoryId() != null) {
            productCategory.setCategoryId(categoryForm.getCategoryId());
        }

        categoryService.save(productCategory);
        map.put("msg", ResultEnum.COMMON_SUCCESS.getMessage());
        return new ModelAndView("common/success.btl", map);
    }
}
